package com.cheng.sell.service.impl;

import com.cheng.sell.VO.CartVO;
import com.cheng.sell.converter.OrderMaster2OrderMasterDTOConverter;
import com.cheng.sell.dao.OrderDetailRepository;
import com.cheng.sell.dao.OrderMasterRepository;
import com.cheng.sell.dto.OrderMasterDTO;
import com.cheng.sell.entity.OrderDetail;
import com.cheng.sell.entity.OrderMaster;
import com.cheng.sell.entity.ProductInfo;
import com.cheng.sell.enums.OrderStatusEnum;
import com.cheng.sell.enums.PayStatusEnum;
import com.cheng.sell.enums.ResultEnum;
import com.cheng.sell.exception.SellException;
import com.cheng.sell.service.OrderMasterService;
import com.cheng.sell.service.ProductInfoService;
import com.cheng.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author chengxintao
 * @version 1.0
 * <p>
 * <p>
 * History:
 * <p>
 * Date                 Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2018/8/24         chengxintao          1.0         To create
 * </p>
 * @see
 * @since
 */
@Service
@Slf4j
public class OrderMasterServiceImpl implements OrderMasterService {


    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private ProductInfoService productInfoService;

    @Override
    @Transactional
    public OrderMasterDTO create(OrderMasterDTO orderMasterDTO) {

        String orderId = KeyUtil.getUniqueKey();
        //总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        //查询商品
        for (OrderDetail orderDetail : orderMasterDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //计算总价
            orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);

            //订单详情入库
            orderDetail.setDetailId(KeyUtil.getUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailRepository.save(orderDetail);

        }


        //写入订单数据(orderMaster/orderDetail)
        OrderMaster orderMaster = new OrderMaster();
        orderMasterDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderMasterDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //扣除库存
        List<CartVO> cartVOList = orderMasterDTO.getOrderDetailList()
                .stream().map(e -> new CartVO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.decreaseStock(cartVOList);

        return orderMasterDTO;
    }

    @Override
    @Transactional
    public OrderMasterDTO cancel(OrderMasterDTO orderMasterDTO) {
        //判断订单状态
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确，orderId={},orderStatus={}", orderMasterDTO.getOrderId(), orderMasterDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_FAILED);
        }
        //修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDTO, orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_FAILED);
        }
        //修改库存
        if (CollectionUtils.isEmpty(orderMasterDTO.getOrderDetailList())) {
            throw new SellException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        List<CartVO> cartVOList = orderMasterDTO.getOrderDetailList()
                .stream().map(e -> new CartVO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.addStock(cartVOList);

        //如果用户已付款 进行退款操作
        if (orderMaster.getPayStatus().equals(PayStatusEnum.SUCCESS)) {
            //TODO
        }

        return orderMasterDTO;
    }

    @Override
    @Transactional
    public OrderMasterDTO end(OrderMasterDTO orderMasterDTO) {
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_FAILED);
        }

        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDTO, orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_FAILED);
        }
        return orderMasterDTO;
    }

    @Override
    public OrderMasterDTO query(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if (orderMaster == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        OrderMasterDTO orderMasterDTO = new OrderMasterDTO();
        BeanUtils.copyProperties(orderMaster, orderMasterDTO);
        orderMasterDTO.setOrderDetailList(orderDetailList);
        return orderMasterDTO;
    }

    @Override
    public Page<OrderMasterDTO> findByBuyerOpenid(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderMasterDTO> orderMasterDTOList = OrderMaster2OrderMasterDTOConverter.convert(orderMasterPage.getContent());
        Page<OrderMasterDTO> orderMasterDTOPage = new PageImpl<OrderMasterDTO>(orderMasterDTOList, pageable, orderMasterPage.getTotalElements());
        return orderMasterDTOPage;
    }

    @Override
    @Transactional
    public OrderMasterDTO paid(OrderMasterDTO orderMasterDTO) {
        //判断订单状态
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_FAILED);
        }
        //判断支付状态
        if (!orderMasterDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_PAY_FAILED);
        }
        //修改支付状态
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDTO, orderMaster);
        orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if (result == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_PAY_FAILED);
        }
        return orderMasterDTO;
    }
}
